import React, { FC, memo, useEffect, useState } from "react"
import { Card, Input, Table, Tooltip } from "antd"
import { ColumnsType } from "antd/es/table"
import { SearchOutlined } from "@ant-design/icons"
import ExtendTabs from "../ExtendTabs"
import { getPerformanceListService } from "@/service/performance"
import { useRequest } from "ahooks"
import { LongTaskType, PagePerformanceType, ResourceType } from "../type"
import { nanoid } from "nanoid"
import { renderValueColor_CLS, renderValueColor_FCP, renderValueColor_INP, renderValueColor_LCP, renderValueColor_TTFB } from "./render-color"

const DataTable: FC = () => {
    const [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([])
    const [searchText, setSearchText] = useState("")
    const { loading, data = [] } = useRequest(getPerformanceListService)
    const [filteredData, setFilteredData] = useState<PagePerformanceType[]>([])
    const [newData, setNewData] = useState<PagePerformanceType[]>([]) // 将 newData 提升为 state
    useEffect(() => {
        // 给resouces和longtasks中的对象添加uid
        const processedData: PagePerformanceType[] = data.map((pageInfo: any) => {
            return {
                ...pageInfo,
                resources: pageInfo.resources.map((item: ResourceType) => {
                    return {
                        ...item,
                        uid: nanoid()
                    }
                }),
                longTasks: pageInfo.longTasks.map((item: LongTaskType) => {
                    return {
                        ...item,
                        uid: nanoid()
                    }
                })
            }
        })
        setNewData(processedData)
        setFilteredData(processedData)
    }, [data])

    const handleSearch = (value: any) => {
        setSearchText(value)
        if (value.trim() === "") {
            setFilteredData(newData)
        } else {
            const filtered = newData.filter((item: PagePerformanceType) => item.url.toLowerCase().includes(value.toLowerCase()))
            setFilteredData(filtered)
        }
    }
    const columns: ColumnsType<PagePerformanceType> = [
        {
            title: (
                <Input
                    placeholder="请输入路由信息"
                    prefix={<SearchOutlined />}
                    value={searchText}
                    style={{ width: "300px" }}
                    onChange={e => handleSearch(e.target.value)}
                />
            ),
            dataIndex: "url",
            key: "url"
        },
        {
            title: "AppId",
            dataIndex: "appId",
            key: "appId"
        },
        {
            title: "PV",
            dataIndex: "pv",
            key: "pv",
            sorter: (a, b) => a.pv - b.pv
        },
        {
            title: "FCP",
            dataIndex: "fcp",
            key: "fcp",
            render: text => renderValueColor_FCP(text),
            sorter: (a, b) => a.fcp - b.fcp
        },
        {
            title: "LCP",
            dataIndex: "lcp",
            key: "lcp",
            render: text => renderValueColor_LCP(text),
            sorter: (a, b) => a.lcp - b.lcp
        },
        {
            title: "INP",
            dataIndex: "inp",
            key: "inp",
            render: text => renderValueColor_INP(text),
            sorter: (a, b) => a.inp - b.inp
        },
        {
            title: "TTFB",
            dataIndex: "ttfb",
            key: "ttfb",
            render: text => renderValueColor_TTFB(text),
            sorter: (a, b) => a.ttfb - b.ttfb
        },
        {
            title: (
                <Tooltip placement="top" title="数值放大了10000倍">
                    <span>CLS</span>
                </Tooltip>
            ),
            dataIndex: "cls",
            key: "cls",
            render: text => renderValueColor_CLS(text)
        }
    ]

    const expandedRowRender = (record: PagePerformanceType) => <ExtendTabs record={record} />

    const expandable = {
        expandedRowRender,
        rowExpandable: (record: any) => record.resources.length > 0,
        expandedRowKeys,
        onExpandedRowsChange: (keys: any) => setExpandedRowKeys(keys)
    }

    return (
        <Card title="页面性能数据" variant="borderless">
            {!loading && <Table rowKey="url" columns={columns} expandable={expandable} dataSource={filteredData} pagination={{ pageSize: 10 }} />}
        </Card>
    )
}

export default memo(DataTable)
